﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using FarseerPhysics;

namespace PulsePrototype.PulseManagers
{
    public class CameraComponent : BaseComponent
    {
        private float aspectRatio;
        public Matrix camTransform;
        public Vector3 camPosition = Vector3.Zero;
        public float camZoom = 1f;

        public float AspectRatio
        {
            get { return aspectRatio; }
        }

        protected override String GetName()
        {
            return "Camera";
        }

        public CameraComponent(BaseEntity ParentEntity) :
            base(ParentEntity)
        {
            Initialize();
        }

        protected override void Initialize()
        {
            // Default aspect ratio is that of the viewport/window
            aspectRatio = this.Parent.Manager.Game.GraphicsDevice.Viewport.AspectRatio;

            base.Initialize();
        }

        public Matrix getTransformation(GraphicsDeviceManager graphic)
        {
            camTransform = Matrix.CreateTranslation(
                new Vector3(-camPosition.X, -camPosition.Y, -camPosition.Z)) *
                Matrix.CreateScale(new Vector3(camZoom, camZoom, camZoom)) *
                Matrix.CreateTranslation(new Vector3(graphic.GraphicsDevice.Viewport.Width * 0.5f,
                                                     graphic.GraphicsDevice.Viewport.Height * 0.5f, 0));

            return camTransform;
        }

        public Matrix getPhysicsTransformation(GraphicsDeviceManager graphic)
        {
            Matrix physicsCam;
            
            Vector3 physicsCamPos = ConvertUnits.ToSimUnits(-camPosition);
            Vector3 physicsCamZoom = new Vector3(camZoom, camZoom, camZoom);

            float screenWidth = graphic.GraphicsDevice.Viewport.Width;
            float screenHeight = graphic.GraphicsDevice.Viewport.Height;

            Vector3 physicsTranslation = ConvertUnits.ToSimUnits(new Vector3(screenWidth * 0.5f, screenHeight * 0.5f, 0));

            physicsCam = 
                Matrix.CreateTranslation(physicsCamPos) *
                Matrix.CreateScale(physicsCamZoom) *
                Matrix.CreateTranslation(physicsTranslation);

            return physicsCam;
        }

        public void Update(GameTime gametime, Vector3 point)
        {
            camPosition = point;
        }
    }
}
